#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/file.h>

int main() {
    const char *filename = "lock_test.txt";
    int fd = open(filename, O_CREAT | O_RDWR, 0644);
    if (fd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    struct flock lock = {
        .l_type = F_WRLCK,    // 写锁
        .l_whence = SEEK_SET,
        .l_start = 0,
        .l_len = 100         // 锁定前 100 字节
    };

    // 尝试非阻塞加锁
    if (fcntl(fd, F_SETLK, &lock) == -1) {
        perror("fcntl F_SETLK");
        printf("文件锁测试失败（可能已被其他进程锁定）\n");
    } else {
        printf("文件锁已设置！\n");

        // 释放锁
        lock.l_type = F_UNLCK;
        if (fcntl(fd, F_SETLK, &lock) == -1) {
            perror("fcntl F_SETLK unlock");
        } else {
            printf("文件锁已释放\n");
        }
    }

    close(fd);
    remove(filename); // 清理测试文件
    return EXIT_SUCCESS;
}
